#pragma once
#include "Socket.hpp"
#include <unistd.h>
#include <sys/socket.h>
#include <functional>
static const std::string peerip = "127.0.0.1";
static const int gport = 8880;

class TcpClient
{
    public:
    TcpClient(std::string ip, uint16_t port = gport)
        : _ip(ip), _port(port), _sock(std::make_shared<TcpSocket>())
    {
        _sock->BuildCilentSocket(_ip, _port);
    }
    static void service(SockPtr sock)
    {
        while (true)
        {
            std::string message;
            std::cout << "Enter #";
            std::getline(std::cin, message);

            if (message.empty()) {
                continue;
            }
            ssize_t wn = ::send(sock->Sockfd(), message.c_str(), message.size(), 0);
            if (wn < 0) {
                perror("send");
                break;
            }

            char echo_buffer[1024];
            int n = ::recv(sock->Sockfd(), echo_buffer, sizeof(echo_buffer), 0);
            if (n > 0)
            {
                echo_buffer[n] = 0;
                std::cout << echo_buffer << std::endl;
            }
            else
            {
                break;
            }
        }
        sock->Close();
    }
    SockPtr getSock()
    {
        return _sock;
    }
private:
    std::string _ip;
    uint16_t _port;
    SockPtr _sock;
};
